package com.ruoyi.web.controller.system;

import cn.hutool.json.JSONObject;
import com.doudou.minio.Minio;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.PhoneUserCode;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.PhoneAndCode;
import com.ruoyi.system.service.IPhoneAndCodeService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 手机号验证码Controller
 *
 * @author ruoyi
 * @date 2025-06-20
 */
@RestController
@RequestMapping("/system/phoneAndCode")
public class PhoneAndCodeController extends BaseController {
    @Autowired
    private IPhoneAndCodeService phoneAndCodeService;

    @Autowired
    private ISysUserService userService;

    @Autowired private RedisCache redisCache;

/**
 * 查询手机号验证码列表
 */
//@PreAuthorize("@ss.hasPermi('system:phoneAndCode:list')")
//@GetMapping("/list")
//    public TableDataInfo list(PhoneAndCode phoneAndCode) {
//        startPage();
//        List<PhoneAndCode> list = phoneAndCodeService.selectPhoneAndCodeList(phoneAndCode);
//        return getDataTable(list);
//    }

    @GetMapping("/list")
    public AjaxResult getPhoneInfo() {
        // 1. 获取缓存列表，先做非空判断
        List<Object> cacheList = redisCache.getCacheList("sms:jilu");
        if (cacheList == null || cacheList.isEmpty()) {
           return AjaxResult.success();
        }

        // 2. 转换为 PhoneUserCode 列表（过滤掉转换失败的数据）
        List<PhoneUserCode> collect = new ArrayList<>();
        for (Object obj : cacheList) {
            try {
                JSONObject json = new JSONObject(obj.toString());
                PhoneUserCode phoneCode = PhoneUserCode.fromJson(json);
                if (phoneCode != null && phoneCode.getSendTime() != null && phoneCode.getSendTime() > 0) {
                    collect.add(phoneCode);
                }
            } catch (Exception e) {
                // 忽略无法解析的对象，避免整个接口因个别脏数据失败
                continue;
            }
        }

        if (collect.isEmpty()) {
            return AjaxResult.success(collect);
        }

        // 3. 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        collect.forEach(phoneCode -> {
            String time = sdf.format(new Date(phoneCode.getSendTime()));
            phoneCode.setTime(time);
        });

        // 4. 提取手机号码集合
        List<String> phones = collect.stream()
                .map(PhoneUserCode::getPhone)
                .distinct()
                .collect(Collectors.toList());

        // 5. 查询用户信息
        List<SysUser> users = userService.selectUserNameByPhones(phones);

        // 6. 构建 Map 用于快速查找 nickName
        Map<String, String> phoneToNickNameMap = users.stream()
                .collect(Collectors.toMap(
                        SysUser::getPostsNumber,
                        SysUser::getNickName,
                        (existing, replacement) -> existing // 避免 key 冲突
                ));

        // 7. 设置 nickName
        collect.forEach(phoneCode ->
                phoneCode.setName(phoneToNickNameMap.getOrDefault(phoneCode.getPhone(), "未知用户")));

        // ✅ 新增：按 sendTime 倒序排序
        collect.sort(Comparator.comparingLong(PhoneUserCode::getSendTime).reversed());

        return AjaxResult.success(collect);
    }

    /**
     * 导出手机号验证码列表
     */
    @PreAuthorize("@ss.hasPermi('system:phoneAndCode:export')")
    @Log(title = "手机号验证码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PhoneAndCode phoneAndCode) {
        List<PhoneAndCode> list = phoneAndCodeService.selectPhoneAndCodeList(phoneAndCode);
        ExcelUtil<PhoneAndCode> util = new ExcelUtil<PhoneAndCode>(PhoneAndCode. class);
        util.exportExcel(response, list, "手机号验证码数据");
    }

    /**
     * 获取手机号验证码详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:phoneAndCode:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(phoneAndCodeService.selectPhoneAndCodeById(id));
    }

    /**
     * 新增手机号验证码
     */
    @PreAuthorize("@ss.hasPermi('system:phoneAndCode:add')")
    @Log(title = "手机号验证码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PhoneAndCode phoneAndCode) {
        return toAjax(phoneAndCodeService.insertPhoneAndCode(phoneAndCode));
    }

    /**
     * 修改手机号验证码
     */
    @PreAuthorize("@ss.hasPermi('system:phoneAndCode:edit')")
    @Log(title = "手机号验证码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PhoneAndCode phoneAndCode) {
        return toAjax(phoneAndCodeService.updatePhoneAndCode(phoneAndCode));
    }

    /**
     * 删除手机号验证码
     */
    @PreAuthorize("@ss.hasPermi('system:phoneAndCode:remove')")
    @Log(title = "手机号验证码", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(phoneAndCodeService.deletePhoneAndCodeByIds(ids));
    }
}
